import UIKit
import QYSDK
import UserNotifications

@main
@objc class AppDelegate: FlutterAppDelegate {
    var userId: String = ""
    var phone: String = ""
    var email: String = ""
    var version: String = ""

    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {

        // 根据编译环境设置不同的 appKey
        let appKey = "8162eaea4e4fa01d3ad2777dcc335430"  // 测试环境的 appKey
        let appNames = "七鱼客服"  // 生产环境的 appName
        
        // 配置 SDK
        let option = QYSDKOption(appKey: appKey)
        option.appName = appNames
        
        // 注册 SDK
        QYSDK.shared().register(with: option)
        
        // 创建 Flutter MethodChannel
        let controller = window?.rootViewController as! FlutterViewController
        let channel = FlutterMethodChannel(name: "com.example.qysdk", binaryMessenger: controller.binaryMessenger)
        
        // 处理来自 Flutter 端的调用
        channel.setMethodCallHandler { [weak self] (call, result) in
            if call.method == "showQYSession" {
              // 获取传递过来的数据
              if let args = call.arguments as? [String: Any] {  // 使用 Dictionary 类型
                  self?.userId = args["userId"] as! String
                  self?.phone = args["phone"] as! String
                  self?.email = args["email"] as! String
                  self?.version = args["version"] as! String
              }
              self?.showQYSession()
              result(nil)
            } 
            else {
                result(FlutterMethodNotImplemented)
            }
        }
        
        GeneratedPluginRegistrant.register(with: self)

        UMConfigure.initWithAppkey("67c169569a16fe6dcd5583f5", channel: "App Store")
        UMConfigure.setLogEnabled(true)

        // 推送相关配置
        // 初始化友盟推送 SDK
        let pushConfig = UMessageRegisterEntity()
        pushConfig.types  = Int(UMessageAuthorizationOptions.badge.rawValue  | UMessageAuthorizationOptions.sound.rawValue  | UMessageAuthorizationOptions.alert.rawValue)
        
        // 注册推送
        UMessage.registerForRemoteNotifications(launchOptions: launchOptions, entity: pushConfig) { (granted, error) in
            if granted {
                // 用户允许推送权限
                print("Push notification granted")
            } else {
                // 用户拒绝推送权限
                print("Push notification denied")
            }
        }
        
        // 设置通知代理
        UNUserNotificationCenter.current().delegate = self
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }

    // 你提供的 showQYSession 方法
    func showQYSession() {
        // 创建 QYSource 对象并配置
        let source = QYSource()
        source.title = "iOS\(self.version)"
        source.urlString = "https://qiyukf.com/"
        
        let userInfo = QYUserInfo()
        userInfo.data = """
        [{
            "key": "real_name",
            "value": "\(self.userId)"
        }, {
            "key": "mobile_phone",
            "value": "\(self.phone)"
        }, {
            "key": "email",
            "value": "\(self.email)"
        }, {
            "index": 0,
            "key": "account",
            "label": "账号",
            "value": "zhangsan",
            "href": "http://example.domain/user/zhangsan"
        }, {
            "index": 1,
            "key": "sex",
            "label": "性别",
            "value": "先生"
        }, {
            "index": 5,
            "key": "reg_date",
            "label": "注册日期",
            "value": "2015-11-16"
        }, {
            "index": 6,
            "key": "last_login",
            "label": "上次登录时间",
            "value": "2015-12-22 15:38:54"
        }, {
            "index": 7,
            "key": "tags",
            "label": "标签",
            "value": "企业,vip"
        }]
        """
        QYSDK.shared().setUserInfo(userInfo)
        
        // 获取 QYSessionViewController
        guard let sessionViewController = QYSDK.shared().sessionViewController() else { return }
                
        // 设置 sessionViewController 属性
        sessionViewController.sessionTitle = "七鱼客服"
        sessionViewController.source = source
        sessionViewController.hidesBottomBarWhenPushed = true
        
        if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene {            
            if let window = windowScene.windows.first(where: { $0.isKeyWindow }) {                
                // 尝试获取导航控制器
                if let navController = window.rootViewController as? UINavigationController {
                    print("Found NavigationController")
                    navController.pushViewController(sessionViewController, animated: true)
                } 
                // 如果根视图是普通视图控制器
                else if let rootVC = window.rootViewController {
                    print("Found RootViewController")
                    let navController = UINavigationController(rootViewController: sessionViewController)
                    rootVC.present(navController, animated: true)
                }
            }
        }
    }

    // 处理苹果推送注册
    override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let tokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
        print("DeviceToken: \(tokenString)")
        
        // 注册设备 token 到友盟推送
        UMessage.registerDeviceToken(deviceToken)
    }
    
}

// MARK: - 推送通知代理方法
extension AppDelegate {
    
    // 前台收到推送通知时的处理
    override func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        
        // 友盟处理通知数据
        UMessage.didReceiveRemoteNotification(userInfo)
        
        // 允许显示通知
        completionHandler([.alert, .sound, .badge])
    }
    
    // 用户点击推送通知时的处理
    override func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        
        // 友盟处理点击的通知数据
        UMessage.didReceiveRemoteNotification(userInfo)
        
        // 在这里可以进行页面跳转或其他操作
        completionHandler()
    }
}
